#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2020/12/18 17:47
    Desc  :
--------------------------------------
"""
from mongoengine import IntField

import common.libs.FakerUtils as faker_utils
from application import app
from common.libs.JsonResponseUtils import JsonResponse
from flask import Blueprint, request

from common.libs.ResultRecordUtils import ResultRecordUtils, GPARecordUtils, ChildFitData
from common.libs.paginationUtils import ListPaginationUtils
from servers.decorator.EnvDecorator import check_env
from servers.models.VariableModel import Variable

base_route = Blueprint('base', __name__)


# 获取全局变量列表
def getVariableList(**kwargs):
    projectId = kwargs.get('projectId')
    if projectId:
        variable = Variable.objects(projectId = projectId).order_by('-id')
        pagination = ListPaginationUtils(variable, page = 1, size = 2147483647)

        return pagination.valueArray()
    return []


@base_route.route('/function/list', methods = ['POST'])
def get_random_function():
    """
    获取随机函数列表
    :return:
    """
    try:
        value = 100
        projectId = request.headers.get('project')
        data = getVariableList(projectId = projectId)
        for attr in dir(faker_utils):
            if callable(getattr(faker_utils, attr)):
                module = getattr(faker_utils, attr).__module__
                if 'FakerUtils' in module:
                    desc = str(getattr(faker_utils, attr).__doc__).strip()
                    data.append(dict(value = value, label = f'${attr}()', desc = desc))
                    value += 1
        return JsonResponse(code = 20000, data = data, message = '请求成功').jsonExit()
    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code = 50000, data = None, message = "系统异常", errors = f'{e}').jsonExit()


@base_route.route('/record/list', methods= ['POST'])
@check_env
def getChildFitList():
    """
    GPA扫描结果
    :return:
    """
    try:
        form = {} if not request.json else dict(request.json)
        organizeId, name, time, status = form.get("organizeId"), form.get("name"), form.get("time"), form.get('status')
        # if organizeId is None or organizeId == "":
        #     return JsonResponse(code=40002, data=None, message="organizeId不能为空").jsonExit()
        result = ResultRecordUtils(organizeId = organizeId)
        data = result.get_result_by_filter(name = name, time = time, status = status)
        return JsonResponse(code = 20000, data = data, message = '请求成功').jsonExit()
    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code = 50000, data = None, message = "系统异常", errors = f'{e}').jsonExit()


@base_route.route('/recordname/list', methods = ['POST'])
@check_env
def recordnameList():
    """
    GPA扫描用户姓名列表
    :return:
    """
    try:
        form = {} if not request.json else dict(request.json)
        organizeId = form.get('organizeId')
        result = ResultRecordUtils(organizeId = organizeId)
        data = result.get_name_list()
        return JsonResponse(code = 20000, data = data, message = '请求成功').jsonExit()
    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code = 50000, data = None, message = "系统异常", errors = f'{e}').jsonExit()


@base_route.route('/record/hospital/list', methods = ['POST', 'GET'])
@check_env
def recordOrganizeList():
    """
    获取礼橙贝机构列表
    :return:
    """

    try:
        childFit = ChildFitData()
        # 获取token
        childFit.get_token()
        # 获取机构列表
        data = childFit.get_organize_list()
        print(data)
        return JsonResponse(code = 20000, data = data).jsonExit()

    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code = 50000, data = None, message = "系统异常", errors = f'{e}').jsonExit()


@base_route.route('/record/edit', methods = ['POST'])
@check_env
def recordEdit():
    """
    GPA结果编辑
    :return:
    """
    # try:
    form = {} if not request.json else dict(request.json)
    evaluationRecordId, result = form.get('evaluationRecordId'), form.get('result')
    if evaluationRecordId is None or evaluationRecordId == "":
        return JsonResponse(code = 40002, message = 'evaluationRecordId不能为空', data = None).jsonExit()

    recordUtils = GPARecordUtils()
    data = recordUtils.set_record_detail(evaluationRecordId = evaluationRecordId, result = result)
    return JsonResponse(code = 20000, data = data).jsonExit()
    # except Exception as e:
    #     app.logger.error(e)
    #     return JsonResponse(code = 50000, data = None, message = "系统异常", errors = f'{e}').jsonExit()


@base_route.route('/record/info', methods = ['POST'])
@check_env
def recordInfo():
    """
    GPA详情查询
    :return:
    """

    try:
        form = {} if not request.json else dict(request.json)
        evaluationRecordId = form.get('evaluationRecordId')
        if evaluationRecordId is None or evaluationRecordId == "":
            return JsonResponse(code = 40002, message = 'evaluationRecordId不能为空', data = None).jsonExit()

        recordUtils = GPARecordUtils()
        data = recordUtils.get_record_detail(evaluationRecordId = evaluationRecordId)
        return JsonResponse(code = 20000, data = data).jsonExit()

    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code = 50000, data = None, message = "系统异常", errors = f'{e}').jsonExit()